import cefsharpAdapter from '../cefsharp'

// === 设置相关处理函数 ===
export async function handleSettingsRequests(method, url, data, params) {
    console.log('🔍 [API] 处理设置请求:', { method, url, data, params })
    
    // GET请求处理
    if (method === 'get') {
        // 获取所有设置数据
        if (/\/settings\/all$/.test(url)) {
            console.log('🔍 [API] 获取所有设置数据')
            try {
                const [
                    localNetworkSettings,
                    hj212NetworkSettings,
                    orayConfig,
                    mqttNetworkSettings
                ] = await Promise.all([
                    cefsharpAdapter.callDbMethod('GetLocalNetworkSettings', {}).catch(error => {
                        console.warn('⚠️ [API] 获取本地网络设置失败:', error)
                        return null
                    }),
                    cefsharpAdapter.callDbMethod('GetHj212NetworkSettings', {}).catch(error => {
                        console.warn('⚠️ [API] 获取HJ212网络设置失败:', error)
                        return null
                    }),
                    cefsharpAdapter.callDbMethod('GetOrayNetworkSettings', {}).catch(error => {
                        console.warn('⚠️ [API] 获取花生壳配置失败:', error)
                        return null
                    }),
                    cefsharpAdapter.callDbMethod('GetAllNetworkMqttSettings', {}).catch(error => {
                        console.warn('⚠️ [API] 获取MQTT网络设置失败:', error)
                        return null
                    })
                ])

                const allSettings = {
                    localNetworkSettings,
                    hj212NetworkSettings,
                    orayConfig,
                    mqttNetworkSettings,
                    timestamp: new Date().toISOString()
                }
                return { code: 0, data: allSettings, message: '获取所有设置数据成功' }
            } catch (error) {
                console.error('❌ [API] 获取所有设置数据失败:', error)
                return { code: -1, data: null, message: error.message || '获取所有设置数据失败' }
            }
        }

        // 获取所有GetAllNetworkMqttSettings
        if (/\/settings\/mqtt-network\/all$/.test(url)) {
            console.log('🔍 [API] 获取所有MQTT网络设置')
            return await cefsharpAdapter.callDbMethod('GetAllNetworkMqttSettings', {})
        }

        // 获取MQTT配置项
        if (/\/settings\/mqtt-network\/ui-config$/.test(url)) {
            console.log('🔍 [API] 获取MQTT配置项')
            return await cefsharpAdapter.callNativeMethod('GetMqttUIConfig', {})
        }

        // 获取MQTT自定义主题列表
        if (/\/settings\/mqtt-network\/custom-topic$/.test(url)) {
            console.log('🔍 [API] 获取MQTT自定义主题列表')
            return await cefsharpAdapter.callDbMethod('GetMqttCustomTopicList', {})
        }

        // 获取MQTT配置列表
        if (/\/settings\/mqtt-network\/configs$/.test(url)) {
            console.log('🔍 [API] 获取MQTT配置列表')
            return await cefsharpAdapter.callDbMethod('GetMqttConfigList', {})
        }
        
        // 导出所有设置数据
        if (/\/settings\/all\/export$/.test(url)) {
            console.log('📤 [API] 导出所有设置数据')
            return await cefsharpAdapter.callDbMethod('ExportAllSettings', {})
        }
        
        // 获取本地网络设置
        if (/\/settings\/local-network$/.test(url)) {
            console.log('🔍 [API] 获取本地网络设置')
            return await cefsharpAdapter.callDbMethod('GetLocalNetworkSettings', {})
        }
        
        // 获取HJ212网络设置
        if (/\/settings\/hj212-network$/.test(url)) {
            console.log('🔍 [API] 获取HJ212网络设置')
            return await cefsharpAdapter.callNativeMethod('GetHj212NetworkSettings', {})
        }

        if (/\/settings\/hj212-system-type$/.test(url)) {
            console.log('🔍 [API] 获取HJ212系统类型')
            return await cefsharpAdapter.callNativeMethod('GetHJ212SystemType', {})
        }        
        
        // 获取花生壳配置
        if (/\/settings\/oray-config$/.test(url)) {
            console.log('🔍 [API] 获取花生壳配置')
            const response = await cefsharpAdapter.callDbMethod('GetOrayNetworkSettings', {})
            if (typeof response === 'string') {
                try {
                    return JSON.parse(response)
                } catch (error) {
                    console.warn('⚠️ [API] 花生壳配置解析失败，使用原始数据:', error)
                    return response
                }
            }
            return response
        }
        
        // 获取花生壳SN
        if (/\/settings\/oray\/sn$/.test(url)) {
            console.log('🔍 [API] 获取花生壳SN', params)
            return await cefsharpAdapter.callNativeMethod('GetOrayGetSn', params)
        }
        
        // 获取花生壳状态
        if (/\/settings\/oray\/status$/.test(url)) {
            console.log('🔍 [API] 获取花生壳运行状态')
            return await cefsharpAdapter.callNativeMethod('GetOrayStatus', params)
        }
        
        // 重启花生壳
        if (/\/settings\/oray\/restart$/.test(url)) {
            console.log('🔄 [API] 重启花生壳')
            return await cefsharpAdapter.callNativeMethod('GetOrayRestart', params)
        }

        // 重置花生壳
        if (/\/settings\/oray\/reset$/.test(url)) {
            console.log('🔄 [API] 重置花生壳')
            return await cefsharpAdapter.callNativeMethod('GetOrayReset', params)
        }

        // 启动花生壳
        if (/\/settings\/oray\/start$/.test(url)) {
            console.log('▶️ [API] 启动花生壳')
            return await cefsharpAdapter.callNativeMethod('GetOrayStart', params)
        }

        // 停止花生壳
        if (/\/settings\/oray\/stop$/.test(url)) {
            console.log('⏹️ [API] 停止花生壳')
            return await cefsharpAdapter.callNativeMethod('GetOrayStop', params)
        }

        // 获取MQTT网络设置
        if (/\/settings\/mqtt-network$/.test(url)) {
            console.log('🔍 [API] 获取MQTT网络设置')
            return await cefsharpAdapter.callDbMethod('GetMqttNetworkSettings', {})
        }
        
        // 获取MQTT配置列表
        if (/\/settings\/mqtt-network\/configs$/.test(url)) {
            console.log('🔍 [API] 获取MQTT配置列表')
            return await cefsharpAdapter.callDbMethod('GetMqttConfigList', {})
        }
        
        // 获取单个MQTT配置
        if (/\/settings\/mqtt-network\/configs\/(.+)$/.test(url)) {
            const match = url.match(/\/settings\/mqtt-network\/configs\/(.+)$/)
            const configId = match[1]
            console.log('🔍 [API] 获取MQTT配置:', configId)
            return await cefsharpAdapter.callDbMethod('GetMqttConfig', { configId })
        }
        
        // 兼容旧的路径
        if (/\/settings$/.test(url)) {
            console.log('🔍 [API] 获取系统设置')
            return await cefsharpAdapter.callDbMethod('GetSystemSettings')
        }
        
        if (/\/settings\/preferences/.test(url)) {
            console.log('🔍 [API] 获取用户偏好设置')
            return await cefsharpAdapter.callDbMethod('GetUserPreferences')
        }
    }

    // POST请求处理
    if (method === 'post') {
        // 重置所有设置数据
        if (/\/settings\/all\/reset$/.test(url)) {
            console.log('🔄 [API] 重置所有设置数据')
            return await cefsharpAdapter.callDbMethod('ResetAllSettings', {})
        }
        
        // 导入所有设置数据
        if (/\/settings\/all\/import$/.test(url)) {
            console.log('📥 [API] 导入所有设置数据')
            return await cefsharpAdapter.callDbMethod('ImportAllSettings', data)
        }
        
        // 重置本地网络设置
        if (/\/settings\/local-network\/reset$/.test(url)) {
            console.log('🔄 [API] 重置本地网络设置')
            return await cefsharpAdapter.callDbMethod('ResetLocalNetworkSettings', {})
        }
        
        // 重置花生壳配置
        if (/\/settings\/oray-config\/reset$/.test(url)) {
            console.log('🔄 [API] 重置花生壳配置')
            return await cefsharpAdapter.callDbMethod('ResetOrayConfig', {})
        }
        
        // 花生壳操作
        if (/\/settings\/oray\/restart$/.test(url)) {
            console.log('🔄 [API] 重启花生壳')
            return await cefsharpAdapter.callDbMethod('RestartOray', {})
        }
        
        if (/\/settings\/oray\/reset$/.test(url)) {
            console.log('🔄 [API] 重置花生壳')
            return await cefsharpAdapter.callDbMethod('ResetOray', {})
        }
        
        if (/\/settings\/oray\/start$/.test(url)) {
            console.log('▶️ [API] 启动花生壳')
            return await cefsharpAdapter.callDbMethod('StartOray', {})
        }
        
        if (/\/settings\/oray\/stop$/.test(url)) {
            console.log('⏹️ [API] 停止花生壳')
            return await cefsharpAdapter.callDbMethod('StopOray', {})
        }
        
        // 添加MQTT配置
        if (/\/settings\/mqtt-network\/configs$/.test(url)) {
            console.log('➕ [API] 添加MQTT配置')
            return await cefsharpAdapter.callDbMethod('AddNetworkMqttSetting', data)
        }
        
        // 复制MQTT配置
        if (/\/settings\/mqtt-network\/configs\/(.+)\/copy$/.test(url)) {
            const match = url.match(/\/settings\/mqtt-network\/configs\/(.+)\/copy$/)
            const configId = match[1]
            console.log('📋 [API] 复制MQTT配置:', configId)
            return await cefsharpAdapter.callDbMethod('CopyMqttConfig', { configId, ...data })
        }
        
        // 重置MQTT配置
        if (/\/settings\/mqtt-network\/configs\/(.+)\/reset$/.test(url)) {
            const match = url.match(/\/settings\/mqtt-network\/configs\/(.+)\/reset$/)
            const configId = match[1]
            console.log('🔄 [API] 重置MQTT配置:', configId)
            return await cefsharpAdapter.callDbMethod('ResetMqttConfig', { configId })
        }
        
        // 兼容旧的路径
        if (/\/settings\/init$/.test(url)) {
            console.log('🔍 [API] 初始化设置')
            return await cefsharpAdapter.callDbMethod('InitializeSettings', data)
        }
    }

    // PUT请求处理
    if (method === 'put') {
        // 保存本地网络设置
        if (/\/settings\/local-network$/.test(url)) {
            console.log('💾 [API] 保存本地网络设置:', data)
            return await cefsharpAdapter.callDbMethod('SaveLocalNetworkSettings', data)
        }
        
        // 保存HJ212网络设置
        if (/\/settings\/hj212-network$/.test(url)) {
            console.log('💾 [API] 保存HJ212网络设置:', data)
            return await cefsharpAdapter.callDbMethod('SaveHj212NetworkSettings', data)
        }
        
        // 保存花生壳配置
        if (/\/settings\/oray-config$/.test(url)) {
            console.log('💾 [API] 保存花生壳配置:', data)
            return await cefsharpAdapter.callDbMethod('SaveOrayNetworkSettings', data)
        }
        
        // 保存MQTT网络设置
        if (/\/settings\/mqtt-network$/.test(url)) {
            console.log('💾 [API] 保存MQTT网络设置:', data)
            return await cefsharpAdapter.callDbMethod('UpdateNetworkMqttSetting', data)
        }
        
        // 更新单个MQTT配置
        if (/\/settings\/mqtt-network\/configs\/(.+)$/.test(url)) {
            const match = url.match(/\/settings\/mqtt-network\/configs\/(.+)$/)
            const configId = match[1]
            console.log('✏️ [API] 更新MQTT配置:', configId)
            return await cefsharpAdapter.callDbMethod('UpdateNetworkMqttSetting', data)
        }
        
        // 兼容旧的路径
        if (/\/settings$/.test(url)) {
            console.log('🔍 [API] 更新系统设置:', data)
            return await cefsharpAdapter.callDbMethod('UpdateSystemSettings', data)
        }
        
        if (/\/settings\/preferences/.test(url)) {
            console.log('🔍 [API] 更新用户偏好设置:', data)
            return await cefsharpAdapter.callDbMethod('UpdateUserPreferences', data)
        }
    }

    // DELETE请求处理
    if (method === 'delete') {
        // 批量删除MQTT配置
        if (/\/settings\/mqtt-network\/configs\/batch$/.test(url)) {
            console.log('🗑️ [API] 批量删除MQTT配置:', data.ids)
            return await cefsharpAdapter.callDbMethod('BatchDeleteMqttConfigs', { configIds: data.ids })
        }
        
        // 删除单个MQTT配置
        if (/\/settings\/mqtt-network\/configs\/(.+)$/.test(url)) {
            const match = url.match(/\/settings\/mqtt-network\/configs\/(.+)$/)
            const configId = match[1]
            console.log('🗑️ [API] 删除MQTT配置:', configId)
            return await cefsharpAdapter.callDbMethod('DeleteNetworkMqttSetting', configId)
        }
        
        // 兼容旧的路径
        if (/\/settings\/reset$/.test(url)) {
            console.log('🔍 [API] 重置设置')
            return await cefsharpAdapter.callDbMethod('ResetSettings')
        }
    }

    return null
}

// === 设置相关工具函数 ===
export function isSettingsEndpoint(url) {
    return /\/settings/.test(url)
}

export function formatSettingsData(data) {
    // 格式化设置数据的通用函数
    return {
        timestamp: new Date().toISOString(),
        ...data
    }
} 